const { validationResult } = require('express-validator')

module.exports = (validations) => {
  return async (req, res, next) => {
    await Promise.all(validations.map((validation) => validation.run(req)))
    const errors = validationResult(req)
    if (errors.isEmpty()) {
      return next()
    }
    var errArr = errors.array()
    var filterErrors = ''
    if (errArr.length > 0) {
      filterErrors = errArr.reduce((prev, cur, index) => {
        return prev + cur.msg + (index !== errArr.length - 1 ? ',' : '')
      }, '')
    } else {
      filterErrors = '传参错误'
    }
    res.status(422).json({ errors: filterErrors })
  }
}
